package cn.edu.cqytxy.util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 数据库工具类
 *
 * @author yinjw
 */
public class DBUtils {

    static String URL = "jdbc:mariadb://47.108.13.41:3306/weapon?characterEncoding=UTF-8";
    static String USERNAME = "weapon";
    static String PWD = "Root@1234";

    /**
     * 数据库连接
     */
    private static Connection CONN;

    /**
     * 获取数据库连接
     * @return  数据连接
     */
    public static Connection getConn() {
        // 判断CONN是否为空，为空则获取连接
        try {
            if (CONN != null && !CONN.isClosed()) {
                // 已经有数据库连接，直接返回
                return CONN;
            }
            // 1、装载驱动程序
            Class.forName("org.mariadb.jdbc.Driver");

            // 2、获取数据库连接
            CONN = DriverManager.getConnection(URL, USERNAME, PWD);
        } catch (Exception e) {
            System.out.println("连接出错");
            e.printStackTrace();
        }
        return CONN;
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConn() {
        try {
            if (CONN != null && !CONN.isClosed()) {
                CONN.close();
            }
        } catch (Exception e) {
            System.out.println("关闭连接出错");
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {

        // 获取数据连接
        Connection connection = DBUtils.getConn();

        // 执行sql语句
        try {
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery("select * from farm_product");
            while (rs.next()) {
                // 控制游标的位置
                int productNo = rs.getInt("farm_product_no");
                String productName = rs.getString("farm_product_name");
                String productType = rs.getString("farm_product_type");
                double productPrice = rs.getDouble("farm_product_price");
                System.out.println(productNo + ";" + productName + ";" +
                        productType + ";" + productPrice);
            }
        } catch (Exception e) {

        }

    }
}
